<script setup>
import { ref, defineProps } from 'vue';
import { useRouter } from 'vue-router';

const emit = defineEmits(["removeCachePageId", "addCachePageId"]);//定义可调用的父组件方法名
const activedKeyIdArray = [];//存放曾经激活tab页的key，用于删除时计算应该激活的tab页
const panes = ref([{
  key: '0',
  title: '首页',
  closable: false,
  path: '/'
}]); //页签数组
const activeKey = ref(panes.value[0].key);//当前激活的tab页的key
activedKeyIdArray.push(panes.value[0].key);
emit('addCachePageId', "Welcome"); //缓存首页组件名称
const $router = useRouter(); //全局路由对象
const add = (paneObj) => { //添加tab页签，选中侧边栏菜单项时调用
  $router.push(paneObj.path);
  let oneTab = getTabByKey(paneObj.key);
  if (oneTab == null) { //页签不存在，创建页签
    emit('addCachePageId', paneObj.path.substring(1));//调用父组件函数，加入组件缓存列表
    setActiveedKeyId(paneObj.key); 
    panes.value.push(paneObj);
  } else {
    setActiveedKeyId(oneTab.key);
  }
}

const remove = targetKey => { //关闭页签函数
  /*
  let lastIndex = 0;
  panes.value.forEach((pane, i) => {
    if (pane.key === targetKey) {
        lastIndex = i - 1;
    }
  });*/
  emit('removeCachePageId', getTabByKey(targetKey).path.substring(1));//删除组件列表，要求组件名称和和路由path一致（例如path=/page1，组件名称由应该时page1。也可以使用路由定义中的name，只要这个值和组件的<script setup name="xxx">标签中name的值保持一致即可）
  panes.value = panes.value.filter(pane => pane.key !== targetKey);

  if (activeKey.value === targetKey) {//关闭的是当前激活的页页签，找到最近一次激活的页签并激活
    let loopFlag = true;
    while(loopFlag) {
      let keyId = activedKeyIdArray.pop();
      if (keyId != targetKey) {
        let oneTab = getTabByKey(keyId)
        if (oneTab != null) {
          setActiveedKeyId(oneTab.key);
          $router.push(oneTab.path);
          break;
        }
      }
    }
  }

  /*
  if (panes.value.length && activeKey.value === targetKey) {
    if (lastIndex >= 0) {
        activeKey.value = panes.value[lastIndex].key;
        activedKeyIdArray.push(panes.value[lastIndex].key);
        $router.push(panes.value[lastIndex].path);
    } else {
        activeKey.value = panes.value[0].key;
        activedKeyIdArray.push(panes.value[0].key);
        $router.push(panes.value[0].path);
    }
  }*/
};

const onEdit = (targetKey, action) => {
  if (action === 'add') {
    add();
  } else {
    remove(targetKey);
  }
};

const selectedTab = (activeKeyId) => { //选择某页签时激活该页签
  let oneTab = getTabByKey(activeKeyId);
  if (oneTab != null) {
    setActiveedKeyId(oneTab.key);
    $router.push(oneTab.path);
  }
};

const getTabByKey = (keyId) => { //根据key获得页签对象
  let rtnValue = null;
  for (let index = 0;index < panes.value.length;index++) {
    if (panes.value[index].key == keyId) {
      rtnValue = panes.value[index];
      break;
    }
  }
  return rtnValue;
};

const setActiveedKeyId = (keyId) => {
  activeKey.value = keyId;
  activedKeyIdArray.push(keyId);
};

const getActiveedKeyId = () => {
  return activeKey.value;
};

defineExpose({ add,remove,getActiveedKeyId });//定义可被父组件调用的组件
</script>
<template>
  <a-tabs v-model:activeKey="activeKey" type="editable-card" @edit="onEdit" :hideAdd="true" @change="selectedTab">
    <a-tab-pane v-for="pane in panes" :key="pane.key" :tab="pane.title" :closable="pane.closable">
    </a-tab-pane>
  </a-tabs>
</template>
<style scoped>
:deep(div.ant-tabs-nav-list div.ant-tabs-tab) {
}
:deep(div.ant-tabs-content-holder) {
  display: none;/*隐藏标签页内容，标签页内容由<router-view>内容替代*/
}
:deep(div.ant-tabs-nav) {
  padding: 2px 2px 0 2px;
  margin: 0;
}
/*
:deep(div.ant-tabs-tab) {
    background-color: #ededed;
}*/
</style>
